package com.xiaode.exce;

import cn.hutool.core.util.StrUtil;

import java.util.List;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.upload.UploadFile;


/**
 * 对系统异常时的统一处理
 */
public class GlobalExceptionInterceptor implements Interceptor {

	@Override
	public void intercept(Invocation inv) {
		
		
		Controller controller = inv.getController();
		controller.getResponse().setHeader("server","BeiFengLiangYue");
		try {
			inv.invoke();
		} catch (Throwable e) {
			
			try {
				List<UploadFile> ufs = controller.getFiles();
				if(ufs != null) {
					for(UploadFile uf : ufs) {
						uf.getFile().delete();
					}
				}
			} catch (Exception ex) {
				
			}
			
			Ret ret = Ret.fail();
			boolean b = StrUtil.contains(e.getMessage(), "Data too long");
			if (b == true){
				ret = Ret.fail().set("error", Kv.by("msg", "传入数据过大，超过数据库限制").set("code", 6004));
				controller.renderJson(ret);
				return;
			}
			ret = Ret.fail().set("error", Kv.by("msg", e.getMessage()).set("code", 6004));
			controller.renderJson(ret);
			return;
		}

	}
}
